package com.atwork.wuhua.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.atwork.wuhua.ConstantsMyself;
import com.atwork.wuhua.R;
import com.atwork.wuhua.adapter.BannerAdapter;
import com.atwork.wuhua.adapter.HpAdapter;
import com.atwork.wuhua.adapter.TypesAdapter;
import com.atwork.wuhua.base.BaseFragment;
import com.atwork.wuhua.bean.BannerBean;
import com.atwork.wuhua.bean.HomePageBean;
import com.atwork.wuhua.bean.TypesBean;
import com.atwork.wuhua.mvp.presenter.HomePagePresenter;
import com.atwork.wuhua.mvp.view.IHomePageFragment;
import com.atwork.wuhua.ui.activity.FieldDetialActivity;
import com.atwork.wuhua.ui.activity.WebViewActivity;
import com.atwork.wuhua.utils.LogUtils;
import com.atwork.wuhua.utils.TypeSelectUtil;
import com.atwork.wuhua.utils.Util;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class HomePageFragment extends BaseFragment implements IHomePageFragment {


    @BindView(R.id.rv_hp)
    RecyclerView rvHp;
    Unbinder unbinder;
    @BindView(R.id.swipe)
    SwipeRefreshLayout swipe;
    @BindView(R.id.ed_search)
    EditText edSearch;

    private RecyclerView rv_types;
    private LinearLayout lly_region, lly_level, lly_distance;
    private TextView tv_region, tv_distance;
    private ImageView imgRegionType, imgLevelTop, imgLevelBoom, imgDistanceTop, imgDistanceBoom;
    private HpAdapter hpAdapter;
    private View headerView, footerView;
    private Banner banner, hotBanner;
    private HomePagePresenter presenter;
    private TypesAdapter typesAdapter;

    private List<HomePageBean.DataBean> homePageBeans;
    private List<HomePageBean.DataBean> hotHomePageBeans;
    private List<String> hotBannerList;
    private List<String> bannerList;
    private List<BannerBean.DataBean> bannerBeans;
    private List<TypesBean.DataBean> typesBeans;


    private int action = MOVE_UPDATA;
    private int total;
    private String mtype = ""; //竞技类型
    private String keywords = "";//搜索关键词 非必须参数
    private String area = "0";//区域
    private String sort = "ASC";
    private String orders = "";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    protected boolean isBindEventBus() {
        return false;
    }

    @Override
    public int intiLayout() {
        return R.layout.fragment_hp;
    }

    @Override
    public void initView() {
        presenter = new HomePagePresenter();
        presenter.attachView(this);
//        presenter.getLatLog();
        presenter.getBanner();
        presenter.getTypes();
        homePageBeans = new ArrayList<>();
        hotHomePageBeans = new ArrayList<>();
        bannerList = new ArrayList<>();
        hotBannerList = new ArrayList<>();
        bannerBeans = new ArrayList<>();
        typesBeans = new ArrayList<>();
        initRecycler();
        RefreshData();
        initScreen();
    }

    private void initRecycler() {
        LinearLayoutManager manager = new LinearLayoutManager(mActivity);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rvHp.setLayoutManager(manager);
        hpAdapter = new HpAdapter(getActivity(), R.layout.item_hp, homePageBeans);
        rvHp.setAdapter(hpAdapter);

        headerView = LayoutInflater.from(mActivity).inflate(R.layout.view_hp_header, null);
        hpAdapter.addHeaderView(headerView);
        footerView = LayoutInflater.from(mActivity).inflate(R.layout.view_no_data, null);

        rv_types = headerView.findViewById(R.id.rv_types);
        LinearLayoutManager typemanger = new LinearLayoutManager(mActivity);
        typemanger.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv_types.setLayoutManager(typemanger);
        typesAdapter = new TypesAdapter(getActivity(), R.layout.item_types, typesBeans);
        rv_types.setAdapter(typesAdapter);

        rv_types.setHasFixedSize(true);
        rv_types.setNestedScrollingEnabled(false);


        hpAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.img_thumb:
                        Intent intent = new Intent(mActivity, FieldDetialActivity.class);
                        intent.putExtra(ConstantsMyself.INTENTID, homePageBeans.get(position).getId());
                        startActivity(intent);
                        break;
                }
            }
        });


        // 竞技类型选择
        typesAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.lly_click:
                        showLoading();
                        for (int i = 0; i < typesBeans.size(); i++) {
                            if (i == position) {
                                typesBeans.get(i).setSelect(true);
                                mtype = typesBeans.get(i).getId();
                            } else {
                                typesBeans.get(i).setSelect(false);
                            }
                        }
                        typesAdapter.setNewData(typesBeans);
                        action = MOVE_UPDATA;
                        presenter.getLists(mtype, 1, keywords, area, orders, sort);

                        break;
                }
            }
        });


    }

    private void RefreshData() {
        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                action = MOVE_UPDATA;
                presenter.getBanner();
                presenter.getLists(mtype, 1, keywords, area, orders, sort);
            }
        });

        hpAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (homePageBeans.size() < total) {
                    action = MOVE_LOADING;
                    presenter.getLists(mtype, homePageBeans.size() / 10 + 1, keywords, area, orders, sort);
                } else {
                    hpAdapter.loadMoreEnd();//数据加载完毕
                }

            }
        }, rvHp);
    }


    //筛选
    private void initScreen() {
        lly_region = headerView.findViewById(R.id.lly_region);
        lly_level = headerView.findViewById(R.id.lly_level);
        lly_distance = headerView.findViewById(R.id.lly_distance);
        tv_region = headerView.findViewById(R.id.tv_region);
        tv_distance = headerView.findViewById(R.id.tv_distance);
        imgRegionType = headerView.findViewById(R.id.img_region_type);

        imgLevelTop = headerView.findViewById(R.id.img_level_top);
        imgLevelBoom = headerView.findViewById(R.id.img_level_boom);
        imgDistanceTop = headerView.findViewById(R.id.img_distance_top);
        imgDistanceBoom = headerView.findViewById(R.id.img_distance_boom);

        TypeSelectUtil typeSelectUtil = new TypeSelectUtil(getActivity(), lly_region, imgRegionType, tv_region,
                lly_level, imgLevelTop, imgLevelBoom, lly_distance, imgDistanceTop, imgDistanceBoom);
        typeSelectUtil.setOnSelectResult(new TypeSelectUtil.OnSelectResultLinstener() {
            @Override
            public void onselect(int type, String code) {
                LogUtils.e("type==>" + type + "==code==>" + code);
                switch (type) {
                    case TypeSelectUtil.REGIN:
                        area = code;
                        action = MOVE_UPDATA;
                        presenter.getLists(mtype, 1, keywords, area, orders, sort);
                        break;
                    case TypeSelectUtil.LEVEL:
                        sort = code;
                        action = MOVE_UPDATA;
                        orders = "star";
                        presenter.getLists(mtype, 1, keywords, area, orders, sort);

                        break;
                    case TypeSelectUtil.DISTANCE:
                        sort = code;
                        action = MOVE_UPDATA;
                        orders = "discount";
                        presenter.getLists(mtype, 1, keywords, area, orders, sort);
                        break;

                }
            }
        });
        edSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                keywords = s.toString().trim();
                if (s.toString().length() == 0) {
                    keywords = "";
                    presenter.getLists(mtype, 1, keywords, area, orders, sort);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }


    @Override
    public void setBannerData(BannerBean bannerData) {
        bannerBeans.clear();
        bannerList.clear();
        bannerBeans.addAll(bannerData.getData());
        for (int i = 0; i < bannerData.getData().size(); i++) {
            bannerList.add(bannerData.getData().get(i).getThumb());
        }
        initBanner(bannerList);
    }

    @Override
    public void setTypesData(TypesBean typesBean) {
        typesBeans.clear();
        typesBeans.addAll(typesBean.getData());
        typesBeans.get(0).setSelect(true);
        mtype = typesBeans.get(0).getId();
        typesAdapter.setNewData(typesBeans);
        presenter.getLists(mtype, 1, keywords, area, orders, sort);

    }

    @Override
    public void setLists(HomePageBean homePageBean) {
        if (action == MOVE_UPDATA) {
            homePageBeans.clear();
        }
        total = homePageBean.getMeta().getTotal();
        hotHomePageBeans.clear();
        hotBannerList.clear();
        homePageBeans.addAll(homePageBean.getData());
        hpAdapter.setNewData(homePageBeans);
        int size = homePageBeans.size() > 5 ? 5 : homePageBeans.size();
        for (int i = 0; i < size; i++) {
            hotHomePageBeans.add(homePageBeans.get(i));
            hotBannerList.add(homePageBeans.get(i).getAlbum().get(0));
        }
        initHotBanner(hotBannerList);
        swipe.setRefreshing(false);
    }

    @Override
    public void noData() {
        total = 0;
        homePageBeans.clear();
        hpAdapter.setNewData(homePageBeans);
        hpAdapter.addFooterView(footerView);
        swipe.setRefreshing(false);
    }


    @OnClick(R.id.tv_search)
    public void onViewClicked() {
        action = MOVE_UPDATA;
        keywords = edSearch.getText().toString().trim();
        presenter.getLists(mtype, 1, keywords, area, orders, sort);
        Util.hideSoftInputFromWindow(getActivity());
    }

    private void initBanner(List<String> bannerList) {
        banner = headerView.findViewById(R.id.banner);
        //设置内置样式，共有六种可以点入方法内逐一体验使用。
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器，图片加载器在下方
        banner.setImageLoader(new BannerAdapter());
        //设置图片网址或地址的集合
        banner.setImages(bannerList);
        //设置轮播的动画效果，内含多种特效，可点入方法内查找后内逐一体验
        banner.setBannerAnimation(Transformer.Default);
        //设置轮播图的标题集合
//        banner.setBannerTitles(list_title);
        //设置轮播间隔时间
        banner.setDelayTime(3000);
        //设置是否为自动轮播，默认是“是”。
        banner.isAutoPlay(true);

        //设置指示器的位置，小点点，左中右。
        banner.setIndicatorGravity(BannerConfig.CENTER)
                //以上内容都可写成链式布局，这是轮播图的监听。比较重要。方法在下面。
                .setOnBannerListener(new OnBannerListener() {
                    @Override
                    public void OnBannerClick(int position) {
                        if (bannerBeans.get(position).getType().equals("1")) {
                            Intent intent = new Intent(mActivity, FieldDetialActivity.class);
                            intent.putExtra(ConstantsMyself.INTENTID, bannerBeans.get(position).getId());
                            startActivity(intent);
                        } else {
                            Intent intent = new Intent(mActivity, WebViewActivity.class);
                            intent.putExtra(ConstantsMyself.INTENTURL, bannerBeans.get(position).getUrl());
                            startActivity(intent);
                        }
                    }
                })
                //必须最后调用的方法，启动轮播图。
                .start();

    }

    private void initHotBanner(List<String> hotBannerList) {
        hotBanner = headerView.findViewById(R.id.hotbanner);
        //设置内置样式，共有六种可以点入方法内逐一体验使用。
        hotBanner.setBannerStyle(BannerConfig.NOT_INDICATOR);
        //设置图片加载器，图片加载器在下方
        hotBanner.setImageLoader(new BannerAdapter());
        //设置图片网址或地址的集合
        hotBanner.setImages(hotBannerList);
        //设置轮播的动画效果，内含多种特效，可点入方法内查找后内逐一体验
        hotBanner.setBannerAnimation(Transformer.Default);
        //设置轮播图的标题集合
//        banner.setBannerTitles(list_title);
        //设置轮播间隔时间
        hotBanner.setDelayTime(3000);
        //设置是否为自动轮播，默认是“是”。
        hotBanner.isAutoPlay(true);

        //设置指示器的位置，小点点，左中右。
        hotBanner.setIndicatorGravity(BannerConfig.CENTER)
                //以上内容都可写成链式布局，这是轮播图的监听。比较重要。方法在下面。
                .setOnBannerListener(new OnBannerListener() {
                    @Override
                    public void OnBannerClick(int position) {
                        Intent intent = new Intent(mActivity, FieldDetialActivity.class);
                        intent.putExtra(ConstantsMyself.INTENTID, hotHomePageBeans.get(position).getId());
                        startActivity(intent);
                    }
                })
                //必须最后调用的方法，启动轮播图。
                .start();


    }

    @Override
    public void initData() {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


}
